<template>
  <div class="progress-bar" ref="progressBar" @click.stop.prevent="clickBtn">
    <div class="inner">
      <div class="progress" ref="progress"></div>
      <div class="progress-btn-wrap" @touchstart.prevent="start" @touchmove.prevent="move" @touchend.prevent="end">
        <div class="progress-btn" ref="progressBtn"></div>
      </div>
    </div>
  </div>
</template>

<script>
  import {prefixStyle} from 'common/js/dom.js';

  const BTNWIDTH = 16;
  const transform = prefixStyle('transform');
  export default {
    props: {
      percent: {type: Number, default: 0}
    },
    data () {
      return {
        touch: {}
      };
    },
    watch: {
      percent (newV) {
        if (newV > 0) {
          let width = this.$refs.progressBar.clientWidth - BTNWIDTH;
          let w = newV * width;
          this._offsetWidth(w);
        }
      }
    },
    methods: {
      start (e) {
        this.touch.initState = true;
        this.touch.startX = e.touches[0].pageX;
        this.touch.left = this.$refs.progress.clientWidth;
      },
      move (e) {
        if (!this.touch.initState) {
          return;
        }
        const distance = e.touches[0].pageX - this.touch.startX;
        const diff = Math.max(0, this.touch.left + distance);
        const offset = Math.min(diff, this.$refs.progressBar.clientWidth - BTNWIDTH);
        this._offsetWidth(offset);
      },
      end () {
        this.touch.initState = false;
        this._resetPercent();
      },
      clickBtn (e) {
        let rect = this.$refs.progressBar.getBoundingClientRect();
        let offset = e.pageX - rect.left;
        this._offsetWidth(offset);
        this._resetPercent();
      },
      _offsetWidth (w) {
        this.$refs.progress.style.width = `${w}px`;
        this.$refs.progressBtn.style[transform] = `translate3d(${w}px,0,0)`;
      },
      _resetPercent () {
        let barW = this.$refs.progressBar.clientWidth - BTNWIDTH;
        let percent = this.$refs.progress.clientWidth / barW;
        this.$emit('percentChange', percent);
      }
    }
  };
</script>

<style lang="less" scoped>
  @import "~common/css/variable.less";

  .progress-bar {
    height: 30px;
    .inner {
      position: relative;
      top: 13px;
      height: 4px;
      background: rgba(0, 0, 0, 0.4);
      .progress {
        position: absolute;
        height: 100%;
        background: @color-theme;
      }
      .progress-btn-wrap {
        position: absolute;
        left: -8px;
        top: -13px;
        width: 30px;
        height: 30px;
        .progress-btn {
          position: relative;
          top: 7px;
          left: 7px;
          box-sizing: border-box;
          width: 16px;
          height: 16px;
          border: 3px solid @color-text;
          border-radius: 50%;
          background: @color-theme;
        }
      }
    }
  }
</style>
